﻿using System;
using System.Linq;
using UnityEngine;

namespace Core.Extension
{
    /// <summary>
    /// 可观察的对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Observable<T>
    {
        private T _value;

        public T Value
        {
            get => _value;
            set
            {
                if (_value != null && !_value.Equals(value))
                {
                    onValueChanged?.Invoke(value);
                }

                _value = value;
            }
        }

        public Observable(T normalValue)
        {
            _value = normalValue;
        }

        public Observable()
        {
        }

        private Action<T> onValueChanged;

        /// <summary>
        /// 添加监听
        /// </summary>
        /// <param name="action">在Value发生改变时触发</param>
        public void AddListener(Action<T> action)
        {
            if (onValueChanged == null || !onValueChanged.GetInvocationList().Contains(action))
            {
                onValueChanged += action;
            }
        }
    }
}